package cn.iocoder.yudao.module.erp.service.report.impl;

import cn.iocoder.yudao.module.erp.controller.admin.report.vo.*;
import cn.iocoder.yudao.module.erp.dal.mysql.exchange.ErpExchangeOrderItemMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.exchange.ErpExchangeOrderMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.product.ErpProductMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.recycle.ErpRecycleOrderItemMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.recycle.ErpRecycleOrderMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.report.ErpMetalReportMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.sale.ErpCustomerMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.stock.ErpStockMapper;
import cn.iocoder.yudao.module.erp.enums.exchange.ErpExchangeItemTypeEnum;
import cn.iocoder.yudao.module.erp.enums.metal.ErpMetalTypeEnum;
import cn.iocoder.yudao.module.erp.service.report.ErpMetalReportService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 贵金属报表统计 Service 实现类
 */
@Service
public class ErpMetalReportServiceImpl implements ErpMetalReportService {

    @Resource
    private ErpRecycleOrderMapper recycleOrderMapper;
    @Resource
    private ErpRecycleOrderItemMapper recycleOrderItemMapper;
    @Resource
    private ErpExchangeOrderMapper exchangeOrderMapper;
    @Resource
    private ErpExchangeOrderItemMapper exchangeOrderItemMapper;
    @Resource
    private ErpProductMapper productMapper;
    @Resource
    private ErpStockMapper stockMapper;
    @Resource
    private ErpCustomerMapper customerMapper;
    @Resource
    private ErpMetalReportMapper metalReportMapper;

    @Override
    public List<ErpMetalTypeAnalysisRespVO> getMetalTypeAnalysis(MetalReportReqVO reqVO) {
        // 获取销售统计
        List<Map<String, Object>> saleStats = metalReportMapper.selectSaleStatsByMetalType(reqVO);
        
        // 获取回收统计
        List<Map<String, Object>> recycleStats = metalReportMapper.selectRecycleStatsByMetalType(reqVO);
        
        // 获取兑换统计
        List<Map<String, Object>> exchangeStats = metalReportMapper.selectExchangeStatsByMetalType(reqVO);
        
        // 获取库存统计
        List<Map<String, Object>> inventoryStats = metalReportMapper.selectInventoryStatsByMetalType(reqVO);
        
        // 合并统计结果
        Map<String, ErpMetalTypeAnalysisRespVO> resultMap = new HashMap<>();
        
        // 处理销售统计
        for (Map<String, Object> stat : saleStats) {
            Integer metalType = (Integer) stat.get("metalType");
            Integer purity = (Integer) stat.get("purity");
            String key = metalType + "-" + purity;
            
            ErpMetalTypeAnalysisRespVO vo = resultMap.computeIfAbsent(key, k -> {
                ErpMetalTypeAnalysisRespVO newVo = new ErpMetalTypeAnalysisRespVO();
                newVo.setMetalType(metalType);
                newVo.setMetalTypeName(ErpMetalTypeEnum.getNameByType(metalType));
                newVo.setPurity(purity);
                newVo.setSaleQuantity(BigDecimal.ZERO);
                newVo.setSaleAmount(BigDecimal.ZERO);
                newVo.setRecycleQuantity(BigDecimal.ZERO);
                newVo.setRecycleAmount(BigDecimal.ZERO);
                newVo.setExchangeQuantity(BigDecimal.ZERO);
                newVo.setExchangeAmount(BigDecimal.ZERO);
                newVo.setInventoryQuantity(BigDecimal.ZERO);
                newVo.setInventoryValue(BigDecimal.ZERO);
                return newVo;
            });
            
            vo.setSaleQuantity((BigDecimal) stat.get("saleQuantity"));
            vo.setSaleAmount((BigDecimal) stat.get("saleAmount"));
        }
        
        // 处理回收统计
        for (Map<String, Object> stat : recycleStats) {
            Integer metalType = (Integer) stat.get("metalType");
            Integer purity = (Integer) stat.get("purity");
            String key = metalType + "-" + purity;
            
            ErpMetalTypeAnalysisRespVO vo = resultMap.computeIfAbsent(key, k -> {
                ErpMetalTypeAnalysisRespVO newVo = new ErpMetalTypeAnalysisRespVO();
                newVo.setMetalType(metalType);
                newVo.setMetalTypeName(ErpMetalTypeEnum.getNameByType(metalType));
                newVo.setPurity(purity);
                newVo.setSaleQuantity(BigDecimal.ZERO);
                newVo.setSaleAmount(BigDecimal.ZERO);
                newVo.setRecycleQuantity(BigDecimal.ZERO);
                newVo.setRecycleAmount(BigDecimal.ZERO);
                newVo.setExchangeQuantity(BigDecimal.ZERO);
                newVo.setExchangeAmount(BigDecimal.ZERO);
                newVo.setInventoryQuantity(BigDecimal.ZERO);
                newVo.setInventoryValue(BigDecimal.ZERO);
                return newVo;
            });
            
            vo.setRecycleQuantity((BigDecimal) stat.get("recycleQuantity"));
            vo.setRecycleAmount((BigDecimal) stat.get("recycleAmount"));
        }
        
        // 处理兑换统计
        for (Map<String, Object> stat : exchangeStats) {
            Integer metalType = (Integer) stat.get("metalType");
            Integer purity = (Integer) stat.get("purity");
            Integer itemType = (Integer) stat.get("itemType");
            String key = metalType + "-" + purity;
            
            ErpMetalTypeAnalysisRespVO vo = resultMap.computeIfAbsent(key, k -> {
                ErpMetalTypeAnalysisRespVO newVo = new ErpMetalTypeAnalysisRespVO();
                newVo.setMetalType(metalType);
                newVo.setMetalTypeName(ErpMetalTypeEnum.getNameByType(metalType));
                newVo.setPurity(purity);
                newVo.setSaleQuantity(BigDecimal.ZERO);
                newVo.setSaleAmount(BigDecimal.ZERO);
                newVo.setRecycleQuantity(BigDecimal.ZERO);
                newVo.setRecycleAmount(BigDecimal.ZERO);
                newVo.setExchangeQuantity(BigDecimal.ZERO);
                newVo.setExchangeAmount(BigDecimal.ZERO);
                newVo.setInventoryQuantity(BigDecimal.ZERO);
                newVo.setInventoryValue(BigDecimal.ZERO);
                return newVo;
            });
            
            // 仅统计兑换新品的兑换量
            if (Objects.equals(itemType, ErpExchangeItemTypeEnum.EXCHANGE_PRODUCT.getType())) {
                vo.setExchangeQuantity((BigDecimal) stat.get("exchangeQuantity"));
                vo.setExchangeAmount((BigDecimal) stat.get("exchangeAmount"));
            }
        }
        
        // 处理库存统计
        for (Map<String, Object> stat : inventoryStats) {
            Integer metalType = (Integer) stat.get("metalType");
            Integer purity = (Integer) stat.get("purity");
            String key = metalType + "-" + purity;
            
            ErpMetalTypeAnalysisRespVO vo = resultMap.computeIfAbsent(key, k -> {
                ErpMetalTypeAnalysisRespVO newVo = new ErpMetalTypeAnalysisRespVO();
                newVo.setMetalType(metalType);
                newVo.setMetalTypeName(ErpMetalTypeEnum.getNameByType(metalType));
                newVo.setPurity(purity);
                newVo.setSaleQuantity(BigDecimal.ZERO);
                newVo.setSaleAmount(BigDecimal.ZERO);
                newVo.setRecycleQuantity(BigDecimal.ZERO);
                newVo.setRecycleAmount(BigDecimal.ZERO);
                newVo.setExchangeQuantity(BigDecimal.ZERO);
                newVo.setExchangeAmount(BigDecimal.ZERO);
                newVo.setInventoryQuantity(BigDecimal.ZERO);
                newVo.setInventoryValue(BigDecimal.ZERO);
                return newVo;
            });
            
            BigDecimal inventoryQuantity = (BigDecimal) stat.get("inventoryQuantity");
            BigDecimal salePrice = (BigDecimal) stat.get("salePrice");
            vo.setInventoryQuantity(inventoryQuantity);
            vo.setInventoryValue(inventoryQuantity.multiply(salePrice));
        }
        
        // 将Map转换为List并按金属类型排序
        return resultMap.values().stream()
                .sorted(Comparator.comparing(ErpMetalTypeAnalysisRespVO::getMetalType)
                        .thenComparing(ErpMetalTypeAnalysisRespVO::getPurity))
                .collect(Collectors.toList());
    }

    @Override
    public ErpProfitAnalysisRespVO getProfitAnalysis(MetalReportReqVO reqVO) {
        // 获取销售统计
        List<Map<String, Object>> saleStats = metalReportMapper.selectSaleStatsByMetalType(reqVO);
        
        // 获取回收统计
        List<Map<String, Object>> recycleStats = metalReportMapper.selectRecycleStatsByMetalType(reqVO);
        
        // 获取兑换统计
        List<Map<String, Object>> exchangeStats = metalReportMapper.selectExchangeStatsByMetalType(reqVO);
        
        // 创建结果对象
        ErpProfitAnalysisRespVO result = new ErpProfitAnalysisRespVO();
        result.setSaleIncome(BigDecimal.ZERO);
        result.setRecycleCost(BigDecimal.ZERO);
        result.setExchangeProfit(BigDecimal.ZERO);
        result.setTotalProfit(BigDecimal.ZERO);
        result.setProfitMargin(BigDecimal.ZERO);
        
        // 按金属类型分组的明细
        Map<Integer, ErpProfitAnalysisRespVO.MetalTypeProfitDetailVO> detailMap = new HashMap<>();
        
        // 计算销售收入
        for (Map<String, Object> stat : saleStats) {
            Integer metalType = (Integer) stat.get("metalType");
            BigDecimal saleAmount = (BigDecimal) stat.get("saleAmount");
            
            // 累加总销售收入
            result.setSaleIncome(result.getSaleIncome().add(saleAmount));
            
            // 按金属类型累加
            ErpProfitAnalysisRespVO.MetalTypeProfitDetailVO detail = getOrCreateMetalTypeDetail(detailMap, metalType);
            detail.setSaleIncome(detail.getSaleIncome().add(saleAmount));
        }
        
        // 计算回收成本
        for (Map<String, Object> stat : recycleStats) {
            Integer metalType = (Integer) stat.get("metalType");
            BigDecimal recycleAmount = (BigDecimal) stat.get("recycleAmount");
            
            // 累加总回收成本
            result.setRecycleCost(result.getRecycleCost().add(recycleAmount));
            
            // 按金属类型累加
            ErpProfitAnalysisRespVO.MetalTypeProfitDetailVO detail = getOrCreateMetalTypeDetail(detailMap, metalType);
            detail.setRecycleCost(detail.getRecycleCost().add(recycleAmount));
        }
        
        // 计算兑换收益（价差）
        Map<Integer, BigDecimal> oldMaterialMap = new HashMap<>();
        Map<Integer, BigDecimal> newProductMap = new HashMap<>();
        
        for (Map<String, Object> stat : exchangeStats) {
            Integer metalType = (Integer) stat.get("metalType");
            Integer itemType = (Integer) stat.get("itemType");
            BigDecimal exchangeAmount = (BigDecimal) stat.get("exchangeAmount");
            
            if (Objects.equals(itemType, ErpExchangeItemTypeEnum.OLD_MATERIAL.getType())) {
                // 旧料回收金额
                oldMaterialMap.put(metalType, oldMaterialMap.getOrDefault(metalType, BigDecimal.ZERO).add(exchangeAmount));
            } else if (Objects.equals(itemType, ErpExchangeItemTypeEnum.EXCHANGE_PRODUCT.getType())) {
                // 兑换新品金额
                newProductMap.put(metalType, newProductMap.getOrDefault(metalType, BigDecimal.ZERO).add(exchangeAmount));
            }
        }
        
        // 计算各金属类型的兑换收益
        for (Integer metalType : newProductMap.keySet()) {
            BigDecimal oldMaterialAmount = oldMaterialMap.getOrDefault(metalType, BigDecimal.ZERO);
            BigDecimal newProductAmount = newProductMap.getOrDefault(metalType, BigDecimal.ZERO);
            BigDecimal exchangeProfit = newProductAmount.subtract(oldMaterialAmount);
            
            // 累加总兑换收益
            result.setExchangeProfit(result.getExchangeProfit().add(exchangeProfit));
            
            // 按金属类型累加
            ErpProfitAnalysisRespVO.MetalTypeProfitDetailVO detail = getOrCreateMetalTypeDetail(detailMap, metalType);
            detail.setExchangeProfit(exchangeProfit);
        }
        
        // 计算总利润和利润率
        result.setTotalProfit(result.getSaleIncome().subtract(result.getRecycleCost()).add(result.getExchangeProfit()));
        if (result.getSaleIncome().compareTo(BigDecimal.ZERO) > 0) {
            result.setProfitMargin(result.getTotalProfit().divide(result.getSaleIncome(), 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")));
        }
        
        // 计算各金属类型的利润和利润率
        for (ErpProfitAnalysisRespVO.MetalTypeProfitDetailVO detail : detailMap.values()) {
            detail.setProfit(detail.getSaleIncome().subtract(detail.getRecycleCost()).add(detail.getExchangeProfit()));
            if (detail.getSaleIncome().compareTo(BigDecimal.ZERO) > 0) {
                detail.setProfitMargin(detail.getProfit().divide(detail.getSaleIncome(), 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")));
            }
        }
        
        // 将Map转换为List并按金属类型排序
        List<ErpProfitAnalysisRespVO.MetalTypeProfitDetailVO> detailList = detailMap.values().stream()
                .sorted(Comparator.comparing(ErpProfitAnalysisRespVO.MetalTypeProfitDetailVO::getMetalType))
                .collect(Collectors.toList());
        
        result.setMetalTypeDetails(detailList);
        
        return result;
    }
    
    /**
     * 获取或创建金属类型盈亏明细VO
     */
    private ErpProfitAnalysisRespVO.MetalTypeProfitDetailVO getOrCreateMetalTypeDetail(
            Map<Integer, ErpProfitAnalysisRespVO.MetalTypeProfitDetailVO> detailMap, Integer metalType) {
        return detailMap.computeIfAbsent(metalType, k -> {
            ErpProfitAnalysisRespVO.MetalTypeProfitDetailVO detail = new ErpProfitAnalysisRespVO.MetalTypeProfitDetailVO();
            detail.setMetalType(metalType);
            detail.setMetalTypeName(ErpMetalTypeEnum.getNameByType(metalType));
            detail.setSaleIncome(BigDecimal.ZERO);
            detail.setRecycleCost(BigDecimal.ZERO);
            detail.setExchangeProfit(BigDecimal.ZERO);
            detail.setProfit(BigDecimal.ZERO);
            detail.setProfitMargin(BigDecimal.ZERO);
            return detail;
        });
    }

    @Override
    public ErpCustomerTransactionRespVO getCustomerTransaction(Long customerId, MetalReportReqVO reqVO) {
        // 获取客户基本交易统计信息
        Map<String, Object> customerStats = metalReportMapper.selectCustomerTransactionStats(customerId, reqVO);
        if (customerStats == null || customerStats.isEmpty()) {
            return new ErpCustomerTransactionRespVO();
        }
        
        // 创建结果对象
        ErpCustomerTransactionRespVO result = new ErpCustomerTransactionRespVO();
        result.setCustomerId(customerId);
        result.setCustomerName((String) customerStats.get("customerName"));
        result.setPurchaseCount(((Number) customerStats.get("purchaseCount")).intValue());
        result.setPurchaseAmount((BigDecimal) customerStats.get("purchaseAmount"));
        result.setRecycleCount(((Number) customerStats.get("recycleCount")).intValue());
        result.setRecycleAmount((BigDecimal) customerStats.get("recycleAmount"));
        result.setExchangeCount(((Number) customerStats.get("exchangeCount")).intValue());
        
        // 按金属类型查询客户的交易记录
        List<Map<String, Object>> saleDetailList = getSaleDetailsByCustomer(customerId, reqVO);
        List<Map<String, Object>> recycleDetailList = getRecycleDetailsByCustomer(customerId, reqVO);
        List<Map<String, Object>> exchangeDetailList = getExchangeDetailsByCustomer(customerId, reqVO);
        
        // 合并按金属类型的交易记录
        Map<String, ErpCustomerTransactionRespVO.CustomerMetalDetailVO> detailMap = new HashMap<>();
        
        // 处理销售记录
        for (Map<String, Object> detail : saleDetailList) {
            Integer metalType = (Integer) detail.get("metalType");
            Integer purity = (Integer) detail.get("purity");
            String key = metalType + "-" + purity;
            
            ErpCustomerTransactionRespVO.CustomerMetalDetailVO detailVO = detailMap.computeIfAbsent(key, k -> {
                ErpCustomerTransactionRespVO.CustomerMetalDetailVO vo = new ErpCustomerTransactionRespVO.CustomerMetalDetailVO();
                vo.setMetalType(metalType);
                vo.setMetalTypeName(ErpMetalTypeEnum.getNameByType(metalType));
                vo.setPurity(purity);
                vo.setPurchaseQuantity(BigDecimal.ZERO);
                vo.setPurchaseAmount(BigDecimal.ZERO);
                vo.setRecycleQuantity(BigDecimal.ZERO);
                vo.setRecycleAmount(BigDecimal.ZERO);
                vo.setExchangeOldQuantity(BigDecimal.ZERO);
                vo.setExchangeNewQuantity(BigDecimal.ZERO);
                return vo;
            });
            
            detailVO.setPurchaseQuantity((BigDecimal) detail.get("quantity"));
            detailVO.setPurchaseAmount((BigDecimal) detail.get("amount"));
        }
        
        // 处理回收记录
        for (Map<String, Object> detail : recycleDetailList) {
            Integer metalType = (Integer) detail.get("metalType");
            Integer purity = (Integer) detail.get("purity");
            String key = metalType + "-" + purity;
            
            ErpCustomerTransactionRespVO.CustomerMetalDetailVO detailVO = detailMap.computeIfAbsent(key, k -> {
                ErpCustomerTransactionRespVO.CustomerMetalDetailVO vo = new ErpCustomerTransactionRespVO.CustomerMetalDetailVO();
                vo.setMetalType(metalType);
                vo.setMetalTypeName(ErpMetalTypeEnum.getNameByType(metalType));
                vo.setPurity(purity);
                vo.setPurchaseQuantity(BigDecimal.ZERO);
                vo.setPurchaseAmount(BigDecimal.ZERO);
                vo.setRecycleQuantity(BigDecimal.ZERO);
                vo.setRecycleAmount(BigDecimal.ZERO);
                vo.setExchangeOldQuantity(BigDecimal.ZERO);
                vo.setExchangeNewQuantity(BigDecimal.ZERO);
                return vo;
            });
            
            detailVO.setRecycleQuantity((BigDecimal) detail.get("quantity"));
            detailVO.setRecycleAmount((BigDecimal) detail.get("amount"));
        }
        
        // 处理兑换记录
        for (Map<String, Object> detail : exchangeDetailList) {
            Integer metalType = (Integer) detail.get("metalType");
            Integer purity = (Integer) detail.get("purity");
            Integer itemType = (Integer) detail.get("itemType");
            String key = metalType + "-" + purity;
            
            ErpCustomerTransactionRespVO.CustomerMetalDetailVO detailVO = detailMap.computeIfAbsent(key, k -> {
                ErpCustomerTransactionRespVO.CustomerMetalDetailVO vo = new ErpCustomerTransactionRespVO.CustomerMetalDetailVO();
                vo.setMetalType(metalType);
                vo.setMetalTypeName(ErpMetalTypeEnum.getNameByType(metalType));
                vo.setPurity(purity);
                vo.setPurchaseQuantity(BigDecimal.ZERO);
                vo.setPurchaseAmount(BigDecimal.ZERO);
                vo.setRecycleQuantity(BigDecimal.ZERO);
                vo.setRecycleAmount(BigDecimal.ZERO);
                vo.setExchangeOldQuantity(BigDecimal.ZERO);
                vo.setExchangeNewQuantity(BigDecimal.ZERO);
                return vo;
            });
            
            BigDecimal quantity = (BigDecimal) detail.get("quantity");
            if (Objects.equals(itemType, ErpExchangeItemTypeEnum.OLD_MATERIAL.getType())) {
                detailVO.setExchangeOldQuantity(quantity);
            } else if (Objects.equals(itemType, ErpExchangeItemTypeEnum.EXCHANGE_PRODUCT.getType())) {
                detailVO.setExchangeNewQuantity(quantity);
            }
        }
        
        // 将Map转换为List并按金属类型排序
        List<ErpCustomerTransactionRespVO.CustomerMetalDetailVO> detailList = detailMap.values().stream()
                .sorted(Comparator.comparing(ErpCustomerTransactionRespVO.CustomerMetalDetailVO::getMetalType)
                        .thenComparing(ErpCustomerTransactionRespVO.CustomerMetalDetailVO::getPurity))
                .collect(Collectors.toList());
        
        result.setMetalDetails(detailList);
        
        return result;
    }
    
    /**
     * 获取客户的销售交易明细
     */
    private List<Map<String, Object>> getSaleDetailsByCustomer(Long customerId, MetalReportReqVO reqVO) {
        // 这里应该使用自定义SQL查询，简化起见此处暂时返回空列表
        // 实际实现应该查询销售订单中按金属类型和纯度分组的数量和金额
        return new ArrayList<>();
    }
    
    /**
     * 获取客户的回收交易明细
     */
    private List<Map<String, Object>> getRecycleDetailsByCustomer(Long customerId, MetalReportReqVO reqVO) {
        // 这里应该使用自定义SQL查询，简化起见此处暂时返回空列表
        // 实际实现应该查询回收订单中按金属类型和纯度分组的数量和金额
        return new ArrayList<>();
    }
    
    /**
     * 获取客户的兑换交易明细
     */
    private List<Map<String, Object>> getExchangeDetailsByCustomer(Long customerId, MetalReportReqVO reqVO) {
        // 这里应该使用自定义SQL查询，简化起见此处暂时返回空列表
        // 实际实现应该查询兑换订单中按金属类型、纯度和项目类型分组的数量和金额
        return new ArrayList<>();
    }

    @Override
    public ErpTrendAnalysisRespVO getTrendAnalysis(MetalTrendReqVO reqVO) {
        // 查询趋势统计数据
        List<Map<String, Object>> trendStatsList = metalReportMapper.selectTrendStatsByTimeGranularity(reqVO);
        
        // 创建结果对象
        ErpTrendAnalysisRespVO result = new ErpTrendAnalysisRespVO();
        result.setMetalType(reqVO.getMetalType());
        result.setMetalTypeName(ErpMetalTypeEnum.getNameByType(reqVO.getMetalType()));
        result.setTimeGranularity(reqVO.getTimeGranularity());
        
        // 将统计数据转换为趋势数据VO
        List<ErpTrendAnalysisRespVO.TrendDataVO> trendDataList = new ArrayList<>();
        for (Map<String, Object> stat : trendStatsList) {
            ErpTrendAnalysisRespVO.TrendDataVO trendData = new ErpTrendAnalysisRespVO.TrendDataVO();
            trendData.setTimePoint((String) stat.get("timePoint"));
            
            // 销售数据
            trendData.setSaleQuantity((BigDecimal) stat.getOrDefault("saleQuantity", BigDecimal.ZERO));
            trendData.setSaleAmount((BigDecimal) stat.getOrDefault("saleAmount", BigDecimal.ZERO));
            
            // 回收数据 - 需要扩展SQL来获取回收数据
            trendData.setRecycleQuantity(BigDecimal.ZERO);
            trendData.setRecycleAmount(BigDecimal.ZERO);
            
            // 金属价格 - 可能需要从外部数据源获取
            trendData.setMetalPrice(calculateAveragePrice(trendData));
            
            trendDataList.add(trendData);
        }
        
        // 填充回收数据
        // 这里需要额外的查询来填充回收数据，简化起见使用空数据
        for (ErpTrendAnalysisRespVO.TrendDataVO trendData : trendDataList) {
            trendData.setRecycleQuantity(BigDecimal.ZERO);
            trendData.setRecycleAmount(BigDecimal.ZERO);
        }
        
        result.setTrendDataList(trendDataList);
        
        return result;
    }
    
    /**
     * 计算平均交易价格
     */
    private BigDecimal calculateAveragePrice(ErpTrendAnalysisRespVO.TrendDataVO trendData) {
        // 简单计算销售均价
        if (trendData.getSaleQuantity().compareTo(BigDecimal.ZERO) > 0) {
            return trendData.getSaleAmount().divide(trendData.getSaleQuantity(), 2, RoundingMode.HALF_UP);
        }
        return BigDecimal.ZERO;
    }

    @Override
    public List<ErpInventoryAnalysisRespVO> getInventoryAnalysis(MetalReportReqVO reqVO) {
        // 查询库存统计数据
        List<Map<String, Object>> inventoryStats = metalReportMapper.selectInventoryStatsByMetalType(reqVO);
        
        // 计算库存总量，用于计算占比
        BigDecimal totalInventoryQuantity = BigDecimal.ZERO;
        for (Map<String, Object> stat : inventoryStats) {
            BigDecimal quantity = (BigDecimal) stat.get("inventoryQuantity");
            totalInventoryQuantity = totalInventoryQuantity.add(quantity);
        }
        
        // 转换结果
        List<ErpInventoryAnalysisRespVO> resultList = new ArrayList<>();
        for (Map<String, Object> stat : inventoryStats) {
            Integer metalType = (Integer) stat.get("metalType");
            Integer purity = (Integer) stat.get("purity");
            BigDecimal inventoryQuantity = (BigDecimal) stat.get("inventoryQuantity");
            BigDecimal salePrice = (BigDecimal) stat.get("salePrice");
            BigDecimal purchasePrice = (BigDecimal) stat.get("purchasePrice");
            
            ErpInventoryAnalysisRespVO vo = new ErpInventoryAnalysisRespVO();
            vo.setMetalType(metalType);
            vo.setMetalTypeName(ErpMetalTypeEnum.getNameByType(metalType));
            vo.setPurity(purity);
            vo.setInventoryQuantity(inventoryQuantity);
            vo.setInventoryValue(inventoryQuantity.multiply(salePrice));
            
            // 计算库存占比
            if (totalInventoryQuantity.compareTo(BigDecimal.ZERO) > 0) {
                vo.setInventoryPercentage(inventoryQuantity.divide(totalInventoryQuantity, 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100")));
            } else {
                vo.setInventoryPercentage(BigDecimal.ZERO);
            }
            
            // 平均成本
            vo.setAverageCost(purchasePrice);
            
            // 当前市场价（这里使用销售价格近似）
            vo.setCurrentMarketPrice(salePrice);
            
            // 潜在收益（市场价 - 成本）* 库存量
            vo.setPotentialProfit(salePrice.subtract(purchasePrice).multiply(inventoryQuantity));
            
            // 库存周转率（这里需要销售和库存数据才能计算，暂时设为0）
            vo.setInventoryTurnoverRate(BigDecimal.ZERO);
            
            resultList.add(vo);
        }
        
        // 按金属类型排序
        return resultList.stream()
                .sorted(Comparator.comparing(ErpInventoryAnalysisRespVO::getMetalType)
                        .thenComparing(ErpInventoryAnalysisRespVO::getPurity))
                .collect(Collectors.toList());
    }

    @Override
    public ErpExchangeAnalysisRespVO getExchangeAnalysis(MetalReportReqVO reqVO) {
        // 查询兑换总体统计数据
        Map<String, Object> overallStats = metalReportMapper.selectExchangeOverallStats(reqVO);
        if (overallStats == null || overallStats.isEmpty()) {
            return new ErpExchangeAnalysisRespVO();
        }
        
        // 创建结果对象
        ErpExchangeAnalysisRespVO result = new ErpExchangeAnalysisRespVO();
        result.setExchangeOrderCount(((Number) overallStats.get("exchangeOrderCount")).intValue());
        result.setExchangeCustomerCount(((Number) overallStats.get("exchangeCustomerCount")).intValue());
        result.setOldMaterialTotalWeight((BigDecimal) overallStats.get("oldMaterialTotalWeight"));
        result.setOldMaterialTotalAmount((BigDecimal) overallStats.get("oldMaterialTotalAmount"));
        result.setNewProductTotalAmount((BigDecimal) overallStats.get("newProductTotalAmount"));
        result.setPriceDifferenceTotalAmount((BigDecimal) overallStats.get("priceDifferenceTotalAmount"));
        
        // 计算新品总重量（需要额外查询）
        result.setNewProductTotalWeight(getExchangeNewProductTotalWeight(reqVO));
        
        // 计算兑换增值率
        if (result.getOldMaterialTotalAmount().compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal valueAddedAmount = result.getNewProductTotalAmount().subtract(result.getOldMaterialTotalAmount());
            result.setValueAddedRate(valueAddedAmount
                    .divide(result.getOldMaterialTotalAmount(), 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100")));
        } else {
            result.setValueAddedRate(BigDecimal.ZERO);
        }
        
        // 按金属类型查询兑换明细统计
        List<ErpExchangeAnalysisRespVO.MetalTypeExchangeDetailVO> metalTypeDetails = getExchangeMetalTypeDetails(reqVO);
        result.setMetalTypeDetails(metalTypeDetails);
        
        return result;
    }
    
    /**
     * 获取兑换新品总重量
     */
    private BigDecimal getExchangeNewProductTotalWeight(MetalReportReqVO reqVO) {
        // 这里应该使用自定义SQL查询新品总重量
        // 简化起见，返回一个示例值
        return new BigDecimal("1000.00");
    }
    
    /**
     * 获取按金属类型分组的兑换明细
     */
    private List<ErpExchangeAnalysisRespVO.MetalTypeExchangeDetailVO> getExchangeMetalTypeDetails(MetalReportReqVO reqVO) {
        // 这里应该使用自定义SQL查询按金属类型分组的兑换明细
        // 简化起见，返回一些示例数据
        List<ErpExchangeAnalysisRespVO.MetalTypeExchangeDetailVO> details = new ArrayList<>();
        
        // 黄金
        ErpExchangeAnalysisRespVO.MetalTypeExchangeDetailVO goldDetail = new ErpExchangeAnalysisRespVO.MetalTypeExchangeDetailVO();
        goldDetail.setMetalType(ErpMetalTypeEnum.GOLD.getType());
        goldDetail.setMetalTypeName(ErpMetalTypeEnum.GOLD.getName());
        goldDetail.setOldMaterialWeight(new BigDecimal("500.00"));
        goldDetail.setOldMaterialAmount(new BigDecimal("250000.00"));
        goldDetail.setNewProductWeight(new BigDecimal("450.00"));
        goldDetail.setNewProductAmount(new BigDecimal("270000.00"));
        goldDetail.setPriceDifference(new BigDecimal("20000.00"));
        goldDetail.setExchangePercentage(new BigDecimal("60.00"));
        details.add(goldDetail);
        
        // 白银
        ErpExchangeAnalysisRespVO.MetalTypeExchangeDetailVO silverDetail = new ErpExchangeAnalysisRespVO.MetalTypeExchangeDetailVO();
        silverDetail.setMetalType(ErpMetalTypeEnum.SILVER.getType());
        silverDetail.setMetalTypeName(ErpMetalTypeEnum.SILVER.getName());
        silverDetail.setOldMaterialWeight(new BigDecimal("800.00"));
        silverDetail.setOldMaterialAmount(new BigDecimal("40000.00"));
        silverDetail.setNewProductWeight(new BigDecimal("750.00"));
        silverDetail.setNewProductAmount(new BigDecimal("45000.00"));
        silverDetail.setPriceDifference(new BigDecimal("5000.00"));
        silverDetail.setExchangePercentage(new BigDecimal("40.00"));
        details.add(silverDetail);
        
        return details;
    }
} 